package com.chery.media.ui.setting.brightness

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.ContactsContract
import android.provider.Settings
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import com.blankj.utilcode.util.LogUtils
import com.chery.media.R
import com.chery.media.databinding.FragmentBrightnessBinding
import com.chery.media.library.base.BaseVMFragment
import com.chery.media.library.base.NoViewModel

class BrightnessFragment: BaseVMFragment<NoViewModel, FragmentBrightnessBinding>() {

    private var register: ActivityResultLauncher<Intent>? = null

    override val layoutId: Int
        get() = R.layout.fragment_brightness

    @RequiresApi(Build.VERSION_CODES.M)
    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        mBinding.brightnessSeekBar.progress = getBrightness()
        if (Settings.System.canWrite(requireActivity()).not()) {
            val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:com.chery.media"))
//            register?.launch(intent)
            startActivityForResult(intent, 1000)
        }
        mBinding.brightnessSeekBar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {

            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                setBrightness(progress)
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {

            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {

            }

        })
    }

    override fun initObserve() {
        register = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) {

        }
    }

    private fun getBrightness(): Int = Settings.System.getInt(requireActivity().contentResolver, Settings.System.SCREEN_BRIGHTNESS, 125)

    private fun setBrightness(int: Int) {
        setBrightnessMode()
        Settings.System.putInt(requireActivity().contentResolver, Settings.System.SCREEN_BRIGHTNESS, int)
    }

    private fun setBrightnessMode(){
        val mode = Settings.System.getInt(requireActivity().contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE)
        if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
            Settings.System.putInt(requireActivity().contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL)
        }
    }

    companion object {
        fun newInstance() = BrightnessFragment()
    }

}